package team.seekers.hula.system.order.controller;

import com.lly835.bestpay.enums.BestPayPlatformEnum;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.service.BestPayService;
import com.lly835.bestpay.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import team.seekers.hula.auth.service.MindUtils;
import team.seekers.hula.common.annotation.ApiResponseBody;
import team.seekers.hula.common.entity.PageResult;
import team.seekers.hula.system.order.entity.dto.OrderCreateReqDTO;
import team.seekers.hula.system.order.entity.dto.OrderListReqDTO;
import team.seekers.hula.system.order.entity.vo.OrderInfoVO;
import team.seekers.hula.system.order.entity.vo.OrderListVO;
import team.seekers.hula.system.order.service.OrderService;

/**
 * @author hbc
 */
@Slf4j
@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private BestPayService bestPayService;

    //创建订单
    @PostMapping("/purchase")
    @ApiResponseBody
    public PayResponse createOrder(@RequestBody OrderCreateReqDTO reqDTO) {
        reqDTO.setUserId(MindUtils.getUserId());
        return orderService.createOrder(reqDTO);
    }


    /**
     * 异步回调
     */
    @PostMapping("/notify")
    public ModelAndView notify(@RequestBody String notifyData) {
        System.out.println("支付回调");
        log.info("【异步通知】支付平台的数据request={}", notifyData);
        PayResponse response = bestPayService.asyncNotify(notifyData);
        log.info("【异步通知】处理后的数据data={}", JsonUtil.toJson(response));

        orderService.notifyPay(response.getOrderId());

        //返回成功信息给支付平台，否则会不停的异步通知
        if (response.getPayPlatformEnum() == BestPayPlatformEnum.WX) {
            return new ModelAndView("pay/responeSuccessForWx");
        }else if (response.getPayPlatformEnum() == BestPayPlatformEnum.ALIPAY) {
            return new ModelAndView("pay/responeSuccessForAlipay");
        }
        throw new RuntimeException("错误的支付平台");
    }



    @GetMapping("/info")
    @ApiResponseBody
    public OrderInfoVO info(@RequestParam String orderId) {
        return orderService.info(orderId);
    }

    //取消订单
    @GetMapping("/cancel")
    @ApiResponseBody
    public void cancelOrder(@RequestParam String id) {
        orderService.cancelOrder(id,MindUtils.getUserId());
    }

    //删除订单
    @GetMapping("/remove")
    @ApiResponseBody
    public void removeOrder(@RequestParam String id) {
        orderService.removeOrder(id,MindUtils.getUserId());
    }

    @GetMapping("/page")
    @ApiResponseBody
    public PageResult<OrderListVO> page(OrderListReqDTO reqDTO) {
        reqDTO.setUserId(MindUtils.getUserId());
        return orderService.page(reqDTO);
    }

}
